package com.example.demo.Interceptor;


import com.example.demo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录拦截器
 *
 * @author zhangkaiqi
 * @date 2021/8/10 9:25:18
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        //获取token
        String token = request.getHeader("token");
        if (token == null) {
            returnJson(response, "{\"code\":4000,\"message\":\"管理员请先登录!\"}");
            return false;
        }
        Claims claims = JwtUtils.checkJwt(token);
        if (claims == null) {
            returnJson(response, "{\"code\":4000,\"message\":\"Token无效，请重新登录!\"}");
            return false;
        }
        if (claims != null) {
            return true;
        }
        if (JwtUtils.isExpiration(token)) {
            returnJson(response, "{\"code\":4000,\"message\":\"Token已过期!\"}");
            return false;
        }
        return false;
    }

    /**
     * 返回客户端数据
     *
     * @param response 响应
     * @param json     JSON字符串
     * @throws Exception 异常
     */
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
